﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Xml;
using Sherwood.Content;
using Sherwood.Content.DO.Model;
using Sherwood.Content.SearchServices;
using Sherwood.Web;
using Xtensive.Storage;
using Record = Sherwood.Content.DO.Model.Record;

namespace Sherwood.Samples.ArticleMeta
{
    public class ArticleMetaSolrXmlInjector : ISolrXmlInjector<Record>
    {
        private readonly IMetaRepository _metaRepository;

        public ArticleMetaSolrXmlInjector(IMetaRepository metaRepository)
        {
            _metaRepository = metaRepository;
        }

        public void Inject(NameValueCollection solrValues, Guid recordId, Record record, object prefetchValues, XmlWriter writer)
        {
             var dict = (Dictionary<Guid, List<ArticleMeta>>)prefetchValues;
            if (recordId == Guid.Empty)
            {
                writer.WriteStartElement("str");
                writer.WriteAttributeString("name", "error");
                writer.WriteValue("SolrRecord does not exist");
                writer.WriteEndElement();
            }
            else
            {
                List<ArticleMeta> metas;
                if (!dict.TryGetValue(recordId, out metas))
                {
                    writer.WriteStartElement("str");
                    writer.WriteAttributeString("name", "error");
                    writer.WriteValue("ArticleMeta does not exist");
                    writer.WriteEndElement();
                }
                else
                {
                    var meta = metas.First();
                
                    writer.WriteStartElement("str");
                    writer.WriteAttributeString("name", "html");
                    writer.WriteCData(meta.Html);
                    writer.WriteEndElement(); 
                    
                    writer.WriteStartElement("str");
                    writer.WriteAttributeString("name", "plain");
                    writer.WriteCData(meta.Body);
                    writer.WriteEndElement();
                }
            }
        }

        public void Prepare(QueryParameterCollection queryString)
        {
            // here we could check for specific settings / parameters and react on them. We may also alter the querystring
        }

        public object Prefetch(IEnumerable<Guid> recordIds, Func<IEnumerable<Record>> getRecords, out bool needsRecordsOnInjection)
        {
            var textMetas = _metaRepository.All.AsQueryable().OfType<Meta>();
            var metas = textMetas.Where(m => m.Record.Id.In(recordIds)).OfType<ArticleMeta>().ToList();

            needsRecordsOnInjection = false;

            return metas.GroupBy(m => m.Record.Id).ToDictionary(g => g.Key, g => g.ToList());
        }
    }
}